﻿using Bystd.Geo.Geometries;
using System.Collections.Generic;

namespace Bystd.Geo.GeoParsers.GeoJson
{
    public class GeoJsonMultiPolygon<T, MPolygon>
          : GeoJsonObject<T, MPolygon> where MPolygon : PolygonMArray
    {
        public GeoJsonMultiPolygon() { }
        public GeoJsonMultiPolygon(Feature<T, MPolygon>[] features)
         : base()
        {
            this.features = features;
        }
    }

    public class GeoJsonMultiPolygon : GeoJsonGeometry
    {
        public List<List<List<double[]>>> coordinates { get; set; }

        public GeoJsonMultiPolygon() { }

        public GeoJsonMultiPolygon(string jsonString)
        {
            var geo = jsonConvert.ConvertTo<GeoJsonMultiPolygon>(jsonString);
            this.coordinates = geo.coordinates;
            this.type = geo.type;
        }

        public GeoJsonMultiPolygon(Geometry geometry)
        {
            this.Geometry = geometry;
        }

        public Geometry ToGeometry()
        {
            List<List<GeoSequence>> seqs = new List<List<GeoSequence>>(coordinates.Count);
            for (int k = 0; k < coordinates.Count; ++k)
            {
                var p = coordinates[k];
                List<GeoSequence> rings = new List<GeoSequence>();

                for (int i = 0; i < p.Count; ++i)
                {
                    var itemArray = p[i];
                    Coordinate[] coords = new Coordinate[itemArray.Count];

                    for (int j = 0; j < coords.Length; ++j)
                    {
                        coords[j] = new Coordinate()
                        {
                            X = itemArray[j][0],
                            Y = itemArray[j][1],
                            Z = itemArray[j].Length >= 3 ? itemArray[j][2] : 0
                        };
                    }
                    rings.Add(new GeoSequence(coords));
                }
                seqs.Add(rings);
            }
            var gtype = GeometryType;
            var geo = new Geometry(gtype, seqs);
            return geo;
        }

        public string FromGeometry()
        {
            this.type = getType();

            coordinates = new List<List<List<double[]>>>(Geometry.GeometryCount);
            foreach (var g in Geometry.Geometric)
            {
                List<List<double[]>> gBuffer = new List<List<double[]>>(g.Count);

                foreach (var line in g)
                {
                    List<double[]> _line = new List<double[]>(line.Count);
                    for (int i = 0; i < line.Count; ++i)
                    {
                        _line.Add(new double[] { line[i].X, line[i].Y });
                    }
                    gBuffer.Add(_line);
                }
                coordinates.Add(gBuffer);
            }
            return jsonConvert.ConvertFrom(this);
        }
    }

}
